package com.ssd.serialize;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * LocalDateTime的自定义序列化器
 * 用于将LocalDateTime对象转换为JSON字符串时，按照指定格式进行序列化
 *
 * @author 86188
 */
public class LocalDateTimeSerializer extends JsonSerializer {
    // 单例实例，保证序列化器的唯一性，节省资源
    public static final LocalDateTimeSerializer instance = new LocalDateTimeSerializer();

    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 判断输入对象是否为LocalDateTime类型
        if (o != null && o instanceof LocalDateTime) {
            // 强制转换为LocalDateTime类型
            LocalDateTime time = (LocalDateTime) o;
            // 使用DateUtil工具类，将LocalDateTime对象格式化为字符串，并写入JSON
            jsonGenerator.writeString(DateUtil.format(time, "yyyy-MM-dd HH:mm:ss"));
        }
    }
}

